package main

import (
	"fmt"
	"log"
	"net"
	"os/exec"
)

func Ping(ip string) string {
	// 创建一个 Command 结构体，指定要执行的命令及其参数
	//cmd := exec.Command("bash", "-c", "ping -c 1 " + ip)	//mac
	//cmd := exec.Command("cmd","/c", "ping", "/n", "1", ip)	//windows

	if !validIP(ip) {
		log.Printf("Error: Invalid ip: %v", ip)
		return ""
	}
	cmd := exec.Command("ping", "-c", "1", ip)	//mac

	// 使用 CombinedOutput 方法执行命令并捕获标准输出和标准错误
	output, err := cmd.CombinedOutput()
	if err != nil {
		log.Printf("Error: %v", err)
		return ""
	}

	// 将输出回显给前端
	return string(output)
}

func Exec(command string, args ...string) string {
	allowedCommands := map[string]bool{
		"ls":   true,
		"pwd":  true,
		"date": true,
		"ping": true,
	}

	if !allowedCommands[command] {
		return fmt.Sprintf("Command: %v not allowed\n", command)
	}

	cmd := exec.Command(command, args...)
	output, err := cmd.Output()
	if err != nil {
		log.Fatal(err)
	}
	return string(output);
}

// 验证 IP 地址
func validIP(ip string) bool {
	return net.ParseIP(ip) != nil
}

func main() {
	//res := Ping("127.0.0.1&whoami")
	//res := Ping("110.242.68.3")

	//output := Exec("ls", "-l", "-h", "-a")
	output := Exec("whoami", "-c", "1", "110.242.68.3")
	fmt.Println(output)
}

